package com.wyl.template.util;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wyl.template.domain.model.SysUserDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Auther: wyl
 * @Date: 2021/4/28
 * @Description: 公共元数据处理器
 */
@Component
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("新建时，开始填充系统字段！");
        Subject subject = SecurityUtils.getSubject();
        SysUserDO userDO = (SysUserDO) subject.getPrincipal();
        // 字段是驼峰类型的，要和DO类中的对应上
        this.strictInsertFill(metaObject, "createTime",
                Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime",
                Date.class, new Date());

        this.strictInsertFill(metaObject, "createBy",
                String.class, userDO.getId().toString());
        this.strictInsertFill(metaObject, "updateBy",
                String.class, userDO.getId().toString());

        this.strictInsertFill(metaObject, "deleted",
                Integer.class, 0);
        this.strictInsertFill(metaObject, "version",
                Long.class, 1L);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新时，开始填充系统字段！");

        Subject subject = SecurityUtils.getSubject();
        SysUserDO userDO = (SysUserDO) subject.getPrincipal();

        this.strictUpdateFill(metaObject, "updateTime",
                LocalDateTime.class, LocalDateTime.now());

        this.strictUpdateFill(metaObject, "updateBy",
                String.class, userDO.getId().toString());
    }
}
